package com.znjc.device.util;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.znjc.common.utils.StringUtils;
import com.znjc.device.domain.DeviceAlarm;
import com.znjc.device.domain.DeviceDevice;
import com.znjc.device.domain.DevicePoint;
import com.znjc.device.domain.IotDataResRule;
import com.znjc.device.domain.vo.PassageVO;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

public class DataUtil {
    /**
     * 数据解析
     *
     * @param data            收到的数据
     * @param acquireStartLen 数据开始解析位置
     * @param dataSliptNum    数据分割位数
     * @return
     */
    public static List<List<String>> analysisData(String data, Integer acquireStartLen, Integer dataSliptNum) {
        List<List<String>> deviceDataList = new ArrayList<>();
        List<String> dataList = packData(data);
        if (CollectionUtils.isNotEmpty(dataList) && dataList.size() > acquireStartLen) {
            List<String> analysisDatas = new ArrayList<>(dataList.subList(acquireStartLen > 0 ? acquireStartLen - 1 : 0, dataList.size()));
            if (CollectionUtils.isNotEmpty(analysisDatas)) {
                //分割数据
                int endIndex = dataSliptNum;
                for (int i = 0; i < analysisDatas.size(); ) {
                    deviceDataList.add(new ArrayList<>(analysisDatas.subList(i, endIndex)));
                    i += dataSliptNum;
                    endIndex += dataSliptNum;
                    if (analysisDatas.size() - i < dataSliptNum) {
                        deviceDataList.add(new ArrayList<>(analysisDatas.subList(i, analysisDatas.size())));
                        break;
                    }
                    if (analysisDatas.size() == i) {
                        break;
                    }
                }
            }
        }
        return deviceDataList;
    }

    /**
     * 处理数据，规避多余的空格，造成下方生成数组时存在null数据
     *
     * @param data
     * @return
     */
    public static List<String> packData(String data) {
        data = data.replaceAll("  ", " ").replaceAll("  ", " ");
        String[] dataArray = data.split(" ");
        List<String> dataList = new ArrayList<>(Arrays.asList(dataArray));
        return dataList;
    }

    /**
     * 封装真实数据集合
     *
     * @param datas
     * @return
     */
    public static String packRealDatas(List<String> datas) {
        List<String> realDatas = new ArrayList<>();
        int s = 0;
        while (CollectionUtils.isNotEmpty(datas) && true) {
            s++;
            int i = datas.indexOf("0B");
            String dataLen = datas.get(i + 1);
            dataLen = String.valueOf(Integer.parseInt(dataLen, 16));
            Integer bitVal = Integer.parseInt(dataLen);
            realDatas = datas.subList(i + 2, datas.size());
            if (CollectionUtils.isNotEmpty(realDatas)) {
                if (realDatas.size() == bitVal) {
                    break;
                } else if (realDatas.size() > bitVal) {
                    datas = datas.subList(i + 1, datas.size());
                } else if (realDatas.size() < bitVal) {
                    realDatas = new ArrayList<>();
                }
            } else {
                break;
            }
            if(s == 5){
                break;
            }
        }
        return realDatas.stream().collect(Collectors.joining(","));
    }

    public static String timestampConvertString(Timestamp timestamp) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd HH:mm:ss.SSS");
        String timeStr = sdf.format(timestamp);
        return timeStr;
    }

    private static void ss(List<String> dataList) {
        dataList = dataList.subList(8, dataList.size());
        System.out.println(dataList.stream().collect(Collectors.joining(",")));
    }

    private static List<String> ss1(List<String> dataList) {
        dataList = dataList.subList(8, dataList.size());
        System.out.println(dataList.stream().collect(Collectors.joining(",")));
        return dataList;
    }

    /**
     * 封装通道号
     *
     * @return
     */
    public static List<PassageVO> getPassageVOs() {
        List<PassageVO> vos = new ArrayList<>();
        PassageVO vo;
        for (int i = 0; i < 8; i++) {
            String val = null;
            if (i > 9) {
                val = Integer.toHexString(i);
            }else{
                val = String.valueOf(i);
            }
            vo = new PassageVO();
            vo.setCode(val);
            vo.setName(val);
            vos.add(vo);
        }
        return vos;
    }

    /**
     * 10进制转16进制
     * @param data
     * @return
     */
    public static String get10To16(Integer data){
        String dataHex = Integer.toHexString(data);
        if(dataHex.length()==1){
            dataHex="000"+dataHex;
        }else if(dataHex.length() == 2){
            dataHex="00"+dataHex;
        }else if(dataHex.length() == 3){
            dataHex="0"+dataHex;
        }
        dataHex = dataHex.substring(0,2) + " " +dataHex.substring(2);
        return dataHex;
    }

    /**
     * 计算data值
     *
     * @param resRule
     * @param data
     */
    public static String getDataValue(IotDataResRule resRule, String data, String operatorUnit) {

        //是否保留小数位
        boolean falg = false;
        if (StringUtils.isNotEmpty(operatorUnit) && !operatorUnit.equals("无") && null != resRule.getRules()) {
            BigDecimal decimal = new BigDecimal(data);
            if (operatorUnit.equals("+")) {
                decimal = decimal.add(resRule.getRules());
                if (resRule.getRules().intValue() == 2000) {
                    falg = true;
                }
            } else if (operatorUnit.equals("-")) {
                decimal = decimal.subtract(resRule.getRules());
            } else if (operatorUnit.equals("*")) {
                decimal = decimal.multiply(resRule.getRules());
            } else if (operatorUnit.equals("/")) {
                decimal = decimal.divide(resRule.getRules());
            }
            //最后要存入数据库的值
            if (falg) {
                data = decimal.setScale(0).toPlainString();
            } else {
                data = decimal.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString();
            }
        }
        return data;
    }

    /**
     * 封装告警列表
     *
     * @param resRule
     * @param data
     * @param deviceBase
     * @param depotPoint
     * @return
     */
    public static DeviceAlarm packAlarm(IotDataResRule resRule, String data, DeviceDevice deviceBase, DevicePoint depotPoint,String thresholdOperators) {
        DeviceAlarm alarm = null;
        //阈值判断--告警判断
        if (StringUtils.isNotEmpty(thresholdOperators) && !"无".equals(thresholdOperators) && null != resRule.getThresholdValue() && StringUtils.isNotEmpty(data)) {
            BigDecimal decimal = new BigDecimal(data);
            if ("小于".equals(thresholdOperators) && decimal.doubleValue() < resRule.getThresholdValue().doubleValue()) {
                alarm = DataUtil.packDeviceAlarm(resRule, false, "0", data, deviceBase, depotPoint, 0);
            } else if ("大于".equals(thresholdOperators) && decimal.doubleValue() > resRule.getThresholdValue().doubleValue()) {
                alarm = DataUtil.packDeviceAlarm(resRule, true, "0", data, deviceBase, depotPoint, 0);
            }
        }
        return alarm;
    }
    /**
     * 封装告警信息
     *
     * @param resRule
     * @param flag    true 高于值 false 低于值
     * @param type    告警类别 0数值告警 1通信告警 2设备故障
     * @param bitNum  位置
     * @return
     */
    public static DeviceAlarm packDeviceAlarm(IotDataResRule resRule, Boolean flag, String type, String data, DeviceDevice deviceBase, DevicePoint depotPoint, int bitNum) {

        DeviceAlarm alarm = new DeviceAlarm();
        alarm.setPointId(depotPoint.getId());
        alarm.setDeviceId(deviceBase.getId());
        alarm.setStartTime(new Date());
        alarm.setAlarmType(type);
        alarm.setRuleWay(resRule.getThresholdOperator());
        alarm.setRuleValue(resRule.getThresholdValue().toPlainString());
        StringBuilder alarmContent = new StringBuilder();
        alarmContent
                .append(deviceBase.getDeviceName())
                .append("_")
                .append(depotPoint.getPointName());
        if ("0".equals(type)) {
            alarmContent.append("的值:")
                    .append(data)
                    .append(flag ? "高于" : "低于")
                    .append("阈值:")
                    .append(resRule.getThresholdValue());
        } else if ("2".equals(type)) {
            alarmContent
                    .append("第")
                    .append(bitNum + 1)
                    .append("位")
                    .append("设备故障。");
        } else if ("1".equals(type)) {
            alarmContent
                    .append("通信故障。");
        }
        alarm.setAlarmContent(alarmContent.toString());
        alarm.setDeptId(resRule.getDeptId());
        alarm.setStatus("0");
        alarm.setCreateBy("admin");
        return alarm;
    }

    public static void main(String[] args) {
        /*//String needData = "F1 01 00 53 0A 02 01 E3 02 19 05 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 03 1B 01 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 0B 15 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0C C5 ";
        String needData = "F1 01 00 36 0A 02 00 EE 02 19 00 00 00 2F CA 00 00 5B A0 00 05 1A E7 00 06 CC 7E 00 08 7E F5 00 0A 30 F2 0B 15 12 13 01 00 00 00 7B 00 00 07 D0 00 00 0C 30 0D AC 00 00 00 00 9D D7 ";
        List<String> dataList = DataUtil.packData(needData);
        dataList.remove(0);
        dataList.remove(0);
        List<String> datas = dataList.subList(0,5);
        System.out.println(datas.stream().collect(Collectors.joining(",")));*/
        /*List<String> datas = dataList.subList(0,dataList.size()-2);
        String data = packRealDatas(datas);
        System.out.println(data);
        System.out.println(data.substring(data.indexOf("12,13,01")+9,data.length()));*/
        /*List<String> dataList1 = new ArrayList<>();
        dataList1.add("1");
        dataList1.add("2");
        while (dataList1.size() > 0){
            dataList1.remove(0);
        }
        System.out.println(dataList1.size());*/
        //1700630293
        //1705732309421
        System.out.println(new BigDecimal("2").multiply(new BigDecimal("3.14").multiply(new BigDecimal("10")).multiply(new BigDecimal("1198"))).setScale(2,BigDecimal.ROUND_HALF_UP).toPlainString());
    }
}
